import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Avatar,
  List,
  Dialog,
  Toast,
  Button,
  Grid
} from 'antd-mobile';
import {
  UserOutline,
  LocationOutline,
  UnorderedListOutline,
  StarOutline,
  CouponOutline,
  SetOutline,
  ExclamationCircleOutline,
} from 'antd-mobile-icons';
import { getUserAvatarPlaceholder } from '../../utils/imageUtils';
import './Profile.css';

const Profile = () => {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState(null);
  const [loading, setLoading] = useState(true);

  // 获取用户信息
  useEffect(() => {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      setUserInfo(JSON.parse(storedUserInfo));
    }
    setLoading(false);
  }, []);

  // 退出登录
  const handleLogout = () => {
    Dialog.confirm({
      content: '确定要退出登录吗？',
      onConfirm: () => {
        localStorage.removeItem('userInfo');
        // 可以保留购物车和订单数据
        Toast.show({
          icon: 'success',
          content: '已退出登录',
        });
        navigate('/login');
      },
    });
  };

  // 检查登录状态
  const checkLogin = (callback) => {
    if (!userInfo) {
      Dialog.confirm({
        content: '请先登录',
        confirmText: '去登录',
        onConfirm: () => {
          navigate('/login');
        },
      });
      return false;
    }
    if (callback) callback();
    return true;
  };

  // 订单状态区块
  const OrderStatusSection = () => {
    const orderItems = [
      { key: 'pending', icon: '付', text: '待付款' },
      { key: 'paid', icon: '发', text: '待发货' },
      { key: 'shipped', icon: '收', text: '待收货' },
      { key: 'completed', icon: '评', text: '待评价' },
      { key: 'afterSale', icon: '退', text: '退换/售后' },
    ];

    return (
      <div className="profile-card profile-order-section">
        <div className="section-header">
          <span>我的订单</span>
          <span
            className="view-all"
            onClick={() => checkLogin(() => navigate('/order/list'))}
          >
            全部订单 &gt;
          </span>
        </div>
        <Grid columns={5} gap={0}>
          {orderItems.map(item => (
            <Grid.Item key={item.key}>
              <div
                className="order-status-item"
                onClick={() => checkLogin(() => navigate(`/order/list?status=${item.key}`))}
              >
                <div className="order-icon">{item.icon}</div>
                <div>{item.text}</div>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
    );
  };

  // 我的服务区块
  const MyServicesSection = () => {
    const services = [
      { key: 'address', icon: <LocationOutline />, text: '收货地址' },
      { key: 'favorites', icon: <StarOutline />, text: '我的收藏' },
      { key: 'coupon', icon: <CouponOutline />, text: '优惠券' },
      { key: 'customer', icon: <SetOutline />, text: '联系客服' },
      { key: 'setting', icon: <SetOutline />, text: '设置' },
      { key: 'about', icon: <ExclamationCircleOutline />, text: '关于我们' },
    ];

    return (
      <div className="profile-card services-section">
        <div className="section-header">
          <span>我的服务</span>
        </div>
        <Grid columns={3} gap={8}>
          {services.map(item => (
            <Grid.Item key={item.key}>
              <div
                className="service-item"
                onClick={() => {
                  if (['address', 'favorites', 'coupon'].includes(item.key)) {
                    checkLogin(() => navigate(`/${item.key}`));
                  } else if (item.key === 'customer') {
                    Toast.show('客服电话: 400-123-4567');
                  } else if (item.key === 'setting') {
                    navigate('/settings');
                  } else if (item.key === 'about') {
                    navigate('/about');
                  }
                }}
              >
                <div className="service-icon">{item.icon}</div>
                <div>{item.text}</div>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
    );
  };

  return (
    <div className="profile-container">
      {/* 用户信息区 */}
      <div className="user-info-section">
        <div className="user-header">
          {userInfo ? (
            <>
              <Avatar
                src={userInfo.avatar || getUserAvatarPlaceholder(userInfo.username, '128x128')}
                style={{ '--size': '64px' }}
              />
              <div className="user-name">{userInfo.username}</div>
            </>
          ) : (
            <>
              <Avatar
                src={getUserAvatarPlaceholder('游客', '128x128')}
                style={{ '--size': '64px' }}
              />
              <Button
                className="login-button"
                size='small'
                color='primary'
                onClick={() => navigate('/login')}
              >
                登录/注册
              </Button>
            </>
          )}
        </div>
      </div>

      {/* 订单状态区 */}
      <OrderStatusSection />

      {/* 我的服务区 */}
      <MyServicesSection />

      {/* 功能列表 */}
      <List className="profile-list">
        <List.Item
          prefix={<UserOutline />}
          onClick={() => checkLogin(() => navigate('/account'))}
        >
          账号管理
        </List.Item>
        <List.Item
          prefix={<LocationOutline />}
          onClick={() => checkLogin(() => navigate('/address'))}
        >
          收货地址
        </List.Item>
        <List.Item
          prefix={<StarOutline />}
          onClick={() => checkLogin(() => navigate('/favorites'))}
        >
          我的收藏
        </List.Item>
        <List.Item
          prefix={<UnorderedListOutline />}
          onClick={() => checkLogin(() => navigate('/order/list'))}
        >
          订单列表
        </List.Item>
      </List>

      {/* 退出按钮 */}
      {userInfo && (
        <div className="logout-button-container">
          <Button
            block
            color='danger'
            onClick={handleLogout}
          >
            退出登录
          </Button>
        </div>
      )}
    </div>
  );
};

export default Profile; 